package com.bjpowernode.tools;

import com.bjpowernode.beans.User;
import com.bjpowernode.services.UserServices;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

public class MyTools {


    public static void loginCookies(HttpServletRequest request, UserServices userServices,LoginCookiesError loginCookiesError) throws Exception {
        String id = "";
        String password = "";
        //判断有没有cookie
        System.out.println("*********开始检测cookies*********：" + request.getRequestURI());
        Cookie[] cookies = request.getCookies();



        //如果cooikes为null
        if(cookies==null){
            System.out.println("*********cookies为null*********：" + request.getRequestURI());
            //执行回调
            loginCookiesError.excute();
            return;
        }


        for (Cookie cookie : cookies) {
            if (cookie.getName().equals("id")) {
                id = cookie.getValue();
            }
            if (cookie.getName().equals("password")) {
                password = cookie.getValue();
            }
        }
        System.out.println("*********开始调用userServices*********：" + request.getRequestURI());
        User loginTemp = userServices.login(id, password);
        System.out.println("*********开始判断用户是否能登录*********：" + request.getRequestURI());
        if (loginTemp == null) {
            System.out.println("*********自动登录失败*********：" + request.getRequestURI());
            //执行回调
            loginCookiesError.excute();
            return;
        }
        System.out.println("*********自动登录成功*********：" + request.getRequestURI());
        request.getSession().setAttribute("user", loginTemp);
    }


    //自定函数内部接口
    @FunctionalInterface
    public interface LoginCookiesError {
        //执行
        void excute() throws Exception;
    }















}
